package cn.queue.file.service.impl;

import cn.queue.file.config.MinioConfig;
import cn.queue.file.service.ISysFileService;
import cn.queue.file.utils.FileUploadUtils;
import com.alibaba.nacos.common.utils.IoUtils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * Minio 文件存储
 *
 * @author queue
 */
@Primary
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        IoUtils.closeQuietly(inputStream);
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

//    @Override
//    public void uploadSlice(MultipartFile file, Long uploadId) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//        String fileName = FileUploadUtils.extractFilename(file);
//        InputStream inputStream = file.getInputStream();
//        PutObjectArgs args = PutObjectArgs.builder()
//                .bucket(minioConfig.getBucketName())
//                .object(fileName)
//                .stream(inputStream, file.getSize(), -1)
//                .contentType(file.getContentType())
//                .build();
//        client.putObject(args);
//        IoUtils.closeQuietly(inputStream);
//    }
}
